﻿$(function() {
	var intervalCounter = 0;
	var app = angular.module('interfaceApp', [ 'toaster', 'ngAnimate',
			'angular-popups' ]);
	app
			.controller(
					'interfaceCtrl',
					function($scope, $http, toaster) {
						// 返回按钮
						$scope.back = function() {
							document.getElementById("exhibitor114").style.display = "block";
							document.getElementById("selectResult").style.display = "none";
							document.getElementById("buttonGroup").style.display = "block";
						}
						// 删除个人全部历史记录
						$scope.deleteAll = function() {
							$http(
									{
										method : 'POST',
										url : "his/deleteAll.do",
										headers : {
											'Content-Type' : 'application/x-www-form-urlencoded'
										},
									}).success(function(data) {// 这里的data，就是后台传递过来的数据
								if (data.tag == "success") {
									toaster.pop({
										type : 'success',
										title : '提示',
										body : "删除成功",
										timeout : 500
									});
									$scope.names = [];
									$scope.resultAll = [];
									$scope.resultAllLength = 0;
									$scope.pageCount = 0;
									$scope.pages = [];
									$scope.p_current = 1;
									$scope.start = 0;
									$scope.end = 0;
								} else {
									toaster.pop({
										type : 'error',
										title : '提示',
										body : "删除失败",
										timeout : 2000
									});
								}
							}).error(function(data, status, headers, config) {
								toaster.pop({
									type : 'error',
									title : '提示',
									body : "请求出错了",
									timeout : 2000
								});

							});

						}
						// 鼠标滑过事件
						$scope.show = function(x) {
							/* toaster.pop('success', "提示", x); */
							toaster.pop({
								type : 'success',
								title : '提示',
								body : x,
								timeout : 1000
							});
						}
						// 主请求方法
						$scope.submitClick = function() {
							$scope.resultMsg = "开始请求，请稍后...";
							// 参数数量
							paramsCount = $("#params").children().children().length;
							methodStr = '';// 请求类型
							urlStr = '';// 请求地址
							paramsMap = {};// 请求参数
							paramsMapChildren = {};// json请求参数
							isContinue = true;// 如果有未输入的参数就改为false不再继续请求了
							if (paramsCount > 2
									&& $("#interfaceUrl").val() != "") {
								document.getElementById("post").checked == true ? methodStr = 'post'
										: methodStr = 'get';
								urlStr = $("#interfaceUrl").val();
								for (i = 1; i < paramsCount - 2; i++) {
									if ($("#paramName" + i).val() == ''
											|| $("#paramValue" + i).val() == '') {
										isContinue = false;
									} else {
										paramsMap[$("#paramName" + i).val()] = encodeURI($(
												"#paramValue" + i).val());
									}
								}
								if (isContinue) {
									if (paramsMap["json"] != undefined
											&& paramsCount == 4) {
										count = $(".BD_tab").children()
												.children().length;
										for (j = 0; j < count; j++) {
											paramsMapChildren[$(
													".paramChildName" + (j + 1))
													.val()] = encodeURI($(
													".paramChildValue"
															+ (j + 1)).val());
										}
										$http(
												{
													method : 'post',
													url : "ask/askForJson.do",
													headers : {
														'Content-Type' : 'application/x-www-form-urlencoded'
													},
													params : {
														urlStr : encodeURI(urlStr),
														methodStr : encodeURI(methodStr),
														paramsMap : paramsMapChildren
													}, // 传递数据作为字符串，从前台传到后台
												}).success(function(data) {// 这里的data，就是后台传递过来的数据
											if (data.tag == "success") {
												$scope.resultMsg = data.result;
											} else {
												$scope.resultMsg = "请求失败了";
											}
										}).error(
												function(data, status, headers,
														config) {
													alert("请求出错了");
												});
									} else {
										$http(
												{
													method : 'post',
													url : "ask/askAndRes.do",
													headers : {
														'Content-Type' : 'application/x-www-form-urlencoded'
													},
													params : {
														urlStr : encodeURI(urlStr),
														methodStr : encodeURI(methodStr),
														paramsMap : paramsMap
													}, // 传递数据作为字符串，从前台传到后台
												}).success(function(data) {// 这里的data，就是后台传递过来的数据
											if (data.tag == "success") {
												$scope.resultMsg = data.result;
											} else {
												$scope.resultMsg = "请求失败了";
											}
										}).error(
												function(data, status, headers,
														config) {
													alert("请求出错了");
												});
									}
								} else {
									toaster.pop({
										type : 'error',
										title : '提示',
										body : "您有未输入的参数项",
										timeout : 500
									});
								}

							} else {
								toaster.pop({
									type : 'error',
									title : '提示',
									body : "请输入请求地址！",
									timeout : 500
								});
							}
						}
						// 识别地址
						$scope.distinguish = function() {
							var fullUrl, url, params, realParams = {};
							var waitUrl = $scope.waitUrl;
							count = $("#params").children().children().length - 3;
							if (waitUrl == '' || waitUrl == undefined) {
								toaster.pop({
									type : 'error',
									title : '提示',
									body : "请输入请求地址！",
									timeout : 500
								});
							} else {
								fullUrl = waitUrl.split("?");
								url = fullUrl[0];
								$("#interfaceUrl").val(url);
								for (a = 0; a < count; a++) {
									document.getElementById("param" + (a + 1)).parentNode
											.removeChild(document
													.getElementById("param"
															+ (a + 1)));
								}
								if (fullUrl[1] == undefined || fullUrl == "") {
								} else {
									params = fullUrl[1].split("&");
									for (j = 0; j < params.length; j++) {
										paramName = "paramName" + (j + 1);
										paramValue = "paramValue" + (j + 1);
										param = "param" + (j + 1);
										$("#params")
												.append(
														"<tr id=\""
																+ param
																+ "\"><td align=\"right\">"
																+ "<input type=\"text\" align=\"right\" size=\"20\" maxlength=\"100\"id=\""
																+ paramName
																+ "\" />"
																+ " :</td><td align=\"left\">"
																+ "<input type=\"text\" align=\"left\" size=\"20\" maxlength=\"100\"id=\""
																+ paramValue
																+ "\" /></td></tr>");

									}
									for (i = 0; i < params.length; i++) {
										var key = (params[i].split("="))[0];
										var values = (params[i].split("="))[1];
										realParams[key] = values;
										$("#paramName" + (i + 1)).val(key);
										$("#paramValue" + (i + 1)).val(values);
									}

								}
							}
						}
						// 显示查询历史记录的结果
						$scope.selectResultClick = function() {
							if ($("#select_btn").val() == "历史") {
								$http(
										{
											method : 'GET',
											url : "his/selectHis.do",
											headers : {
												'Content-Type' : 'application/x-www-form-urlencoded'
											},
										})
										.success(
												function(data) {// 这里的data，就是后台传递过来的数据
													if (data.tag == "success") {
														for (i = 0; i < data.result.length; i++) {
															var newDate = new Date();
															newDate
																	.setTime(data.result[i].time);
															data.result[i].time = newDate
																	.format('yyyy-MM-dd h:m:s');
														}
														// 所有查询出来的历史记录
														$scope.resultAll = data.result;
														// 计算结果总数
														$scope.resultAllLength = $scope.resultAll.length;
														// 计算总页码
														$scope.pageCount = Math
																.ceil($scope.resultAllLength / 10);
														// 本页面的记录
														$scope.names = [];
														for (var a = 0; a < 10; a++) {
															if (a < $scope.resultAllLength) {
																$scope.names
																		.push($scope.resultAll[a]);
															}
														}
														$scope.x = $scope.names;
														// 总页码加入到数组里面
														$scope.pages = $scope
																.calculateIndexes($scope.pageCount);
														$scope.p_current = 1;

													} else {
														$scope.resultAllLength = 0;
														toaster.pop({
															type : 'error',
															title : '提示',
															body : "无查询结果",
															timeout : 2000
														});
													}
													$scope
															.beginAndEnd($scope.p_current);
												}).error(
												function(data, status, headers,
														config) {

													toaster.pop({
														type : 'error',
														title : '提示',
														body : "请求出错了",
														timeout : 2000
													});
												});

								document.getElementById("selectResult").style.display = "block";
								document.getElementById("exhibitor114").style.display = "none";
								document.getElementById("buttonGroup").style.display = "none";
							}
						}
						// 创建当前正在编辑的对象
						$scope.currentStu = {};

						$scope.researchStu = function(x) {
							$scope.research = x;
						};

						// 分页算法
						$scope.calculateIndexes = function(x) {
							var indexes = [];
							for (var i = 1; i <= x; i++) {
								indexes.push(i);
							}
							return indexes;
						};
						// 计算第一条和最后一条是多少？
						$scope.beginAndEnd = function(p_current) {
							$scope.start = (p_current - 1) * 10 + 1;
							$scope.end = (p_current) * 10;
							if ($scope.resultAllLength < 1) {
								$scope.resultAllLength = 0;
								$scope.start = 0;
								$scope.end = 0;
							}
							if ($scope.end > $scope.resultAllLength) {
								$scope.end = $scope.resultAllLength;
							}
						}

						// 加载页面
						$scope.load_page = function(page) {
							if (page < 1) {
								toaster.pop({
									type : 'error',
									title : '提示',
									body : "已经是第一页了",
									timeout : 2000
								});
							} else if (page > $scope.pageCount) {
								toaster.pop({
									type : 'error',
									title : '提示',
									body : "已经是最后一页了",
									timeout : 2000
								});
							} else {
								$scope.p_current = page;
								$scope.names = [];
								for (var a = (page - 1) * 10; a < (page) * 10; a++) {
									if (a < $scope.resultAll.length) {
										$scope.names.push($scope.resultAll[a]);
									}
								}
								$scope.beginAndEnd($scope.p_current);
							}
						}
						// 再次请求
						$scope.btnAgain = function(x) {
							document.getElementById("exhibitor114").style.display = "block";
							document.getElementById("selectResult").style.display = "none";
							document.getElementById("buttonGroup").style.display = "block";
							if (x.methodtype == 'get') {
								document.getElementById("get").checked = true;
								document.getElementById("postText").color = "";
								document.getElementById("getText").color = "blue";
								document.getElementById("post").checked = false;
							} else {
								document.getElementById("post").checked = true;
								document.getElementById("getText").color = "";
								document.getElementById("postText").color = "blue";
								document.getElementById("get").checked = false;
							}
							var params, realParams = {};
							count = $("#params").children().children().length - 3;
							$("#interfaceUrl").val(x.url);
							$scope.resultMsg = "";
							for (a = 0; a < count; a++) {
								document.getElementById("param" + (a + 1)).parentNode
										.removeChild(document
												.getElementById("param"
														+ (a + 1)));
							}
							params = x.params.split("&");
							if (params == undefined || params == "") {
							} else if (params.length == 1) {
								paramName = "paramName" + (1);
								paramValue = "paramValue" + (1);
								param = "param" + (1);
								$("#params")
										.append(
												"<tr id=\""
														+ param
														+ "\"><td align=\"right\">"
														+ "<input type=\"text\" align=\"right\" size=\"20\" maxlength=\"100\"id=\""
														+ paramName
														+ "\" />"
														+ " :</td><td align=\"left\">"
														+ "<input type=\"text\" align=\"left\" size=\"20\" maxlength=\"100\"id=\""
														+ paramValue
														+ "\" /></td></tr>");
								$("#paramName" + (1)).val("json");
								$("#paramValue" + (1)).val(params[0]);
							} else {
								for (j = 0; j < params.length; j++) {
									paramName = "paramName" + (j + 1);
									paramValue = "paramValue" + (j + 1);
									param = "param" + (j + 1);
									$("#params")
											.append(
													"<tr id=\""
															+ param
															+ "\"><td align=\"right\">"
															+ "<input type=\"text\" align=\"right\" size=\"20\" maxlength=\"100\"id=\""
															+ paramName
															+ "\" />"
															+ " :</td><td align=\"left\">"
															+ "<input type=\"text\" align=\"left\" size=\"20\" maxlength=\"100\"id=\""
															+ paramValue
															+ "\" /></td></tr>");

								}
								for (i = 0; i < params.length; i++) {
									var key = (params[i].split("="))[0];
									var values = (params[i].split("="))[1];
									$("#paramName" + (i + 1)).val(key);
									$("#paramValue" + (i + 1)).val(values);
								}
							}
						};
						// 删除历史记录
						$scope.deleteStu = function(x) {
							$http(
									{
										method : 'POST',
										url : "his/deleteHis.do",
										headers : {
											'Content-Type' : 'application/x-www-form-urlencoded'
										},
										params : {
											hisId : x.hisId
										}
									}).success(function(data) {// 这里的data，就是后台传递过来的数据
								if (data.tag == "success") {
									toaster.pop({
										type : 'success',
										title : '提示',
										body : "删除成功",
										timeout : 500
									});

								} else {
									toaster.pop({
										type : 'error',
										title : '提示',
										body : "删除失败",
										timeout : 2000
									});
								}
							}).error(function(data, status, headers, config) {
								toaster.pop({
									type : 'error',
									title : '提示',
									body : "请求出错了",
									timeout : 2000
								});
							});
							$scope.names.splice($scope.names.indexOf(x), 1);
						};
						// 多选然后标识
						var signGroup = [];
						$scope.isSelected = function(currentrow, isCheck) {
							if (isCheck == true) {
								console.info(signGroup.push(currentrow.hisId));
							} else {
								signGroup.remove(currentrow.hisId);
							}
							return currentrow;
						}
						$scope.signClick = function(x) {
							if (x == undefined) {
								toaster.pop({
									type : 'error',
									title : '提示',
									body : "请输入标识内容",
									timeout : 2000
								});
							} else {
								if (signGroup.length < 1) {
									toaster.pop({
										type : 'error',
										title : '提示',
										body : "您未选择任何需要标识的项",
										timeout : 2000
									});
								} else {
									$http(
											{
												method : 'post',
												url : "his/signHis.do",
												headers : {
													'Content-Type' : 'application/x-www-form-urlencoded'
												},
												params : {
													signGroup : encodeURI(signGroup),
													signText : encodeURI(x)
												}, // 传递数据作为字符串，从前台传到后台
											})
											.success(
													function(data) {// 这里的data，就是后台传递过来的数据
														if (data.tag == "success") {
															for (i = 0; i < $scope.names.length; i++) {
																for (j = 0; j < signGroup.length; j++) {
																	if ($scope.names[i].hisId == signGroup[j]) {
																		$scope.names[i].signText = x;
																	}
																}
															}
														} else {
															toaster.pop({
																type : 'error',
																title : '提示',
																body : "标识失败",
																timeout : 2000
															});
														}
													}).error(
													function(data, status,
															headers, config) {
														alert("请求出错了");
													});
								}
							}
						}
					});
	getDate();
	// 第一个参数是按钮的class属性值，第二个是被隐藏的div属性值
	popupLayer("but_tj", "Popup");
	closeLayer("Close", "Popup");
	// 底部渐隐效果
	$("#bottom").click(function() {
		$(this).fadeOut(1000).fadeIn(1000);
	});
	// 添加参数
	$("#paramAdd")
			.click(
					function() {
						count = $("#params").children().children().length - 3;
						paramName = "paramName" + (count + 1);
						paramValue = "paramValue" + (count + 1);
						param = "param" + (count + 1);
						$("#params")
								.append(
										"<tr id=\""
												+ param
												+ "\"><td align=\"right\">"
												+ "<input type=\"text\" align=\"right\" size=\"20\" maxlength=\"100\"id=\""
												+ paramName
												+ "\" />"
												+ " :</td><td align=\"left\">"
												+ "<input type=\"text\" align=\"left\" size=\"20\" maxlength=\"100\"id=\""
												+ paramValue
												+ "\" /></td></tr>");
					});
	// 删除参数
	$("#paramDelete").click(function() {
		count = $("#params").children().children().length - 3;
		param = "#param" + (count);
		$(param).remove();
	});
	// 添加子参数
	$(".paramAddChild")
			.click(
					function() {
						count = $(".BD_tab").children().children().length;
						paramChildName = "paramChildName" + (count + 1);
						paramChildValue = "paramChildValue" + (count + 1);
						tr = "tr" + (count + 1);
						$(".BD_tab")
								.append(
										"<tr class="
												+ tr
												+ "><td style=\"width: 110px;\" align=\"right\">"
												+ "<input type=\"text\" class="
												+ paramChildName
												+ ">"
												+ "</td><td>"
												+ "<input name=\"\" id=\"name\" type=\"text\" class="
												+ paramChildValue
												+ ">"
												+ "<font color=\"red\">*</font></td></tr>");
					});
	// 删除子参数
	$(".paramDeleteChild").click(function() {
		count = $(".BD_tab").children().children().length;
		tr = ".tr" + count;
		$(tr).remove();

	});
	// 保障只有一个radio被选中
	$("#post").click(function() {
		document.getElementById("post").checked = true;
		document.getElementById("getText").color = "";
		document.getElementById("postText").color = "blue";
		document.getElementById("get").checked = false;
	});
	$("#get").click(function() {
		document.getElementById("get").checked = true;
		document.getElementById("postText").color = "";
		document.getElementById("getText").color = "blue";
		document.getElementById("post").checked = false;
	});
	// 点击提交按钮
	$("#submit_aaa")
			.click(
					function() {
						paramsCount = $("#params").children().children().length;
						jsonStr = '';
						if (paramsCount > 3 && $("#interfaceUrl").val() != "") {
							$("#post").attr("checked") == "checked" ? jsonStr = '"ask":"post"'
									: jsonStr = '"ask":"get"';
							jsonStr += ',"url":"' + $("#interfaceUrl").val()
									+ '"';
							for (i = 1; i < paramsCount - 2; i++) {
								jsonStr += (',"' + $("#paramName" + i).val()
										+ '":"' + $("#paramValue" + i).val() + '"');
							}
						} else {
							toaster.pop({
								type : 'error',
								title : '提示',
								body : "参数有误！",
								timeout : 500
							});
						}
						jsonStr = '{' + jsonStr + '}';
						alert(jsonStr);
					});
	// 关闭弹出框
	$(".ClosePopu").click(function() {
		$(".Popup").hide(1000);
		$("#spm").hide();
	});
});
function getDate() {
	// 获取系统时间。
	$("#bottom").css("width", $(window).width());
	var dateTime = new Date();
	var yy = dateTime.getFullYear();
	var dd = dateTime.getDate();
	var mo = dateTime.getMonth() + 1;
	var hh = dateTime.getHours();
	var mm = dateTime.getMinutes();
	var ss = dateTime.getSeconds();
	var week = dateTime.getDay();
	switch (week) {
	case 1:
		week = "星期一";
		break;
	case 2:
		week = "星期二";
		break;
	case 3:
		week = "星期三";
		break;
	case 4:
		week = "星期四";
		break;
	case 5:
		week = "星期五";
		break;
	case 6:
		week = "星期六";
		break;
	case 7:
		week = "星期日";
		break;
	}
	// 分秒时间是一位数字，在数字前补0。
	yy = extra(yy);
	dd = extra(dd);
	mo = extra(mo);
	mm = extra(mm);
	ss = extra(ss);
	// 将时间显示到ID为time的位置，时间格式形如：19:18:02
	$("#time").text(
			yy + "年" + mo + "月" + dd + "日" + "  " + hh + ":" + mm + ":" + ss
					+ "  " + week);
	// 每隔1000ms执行方法systemTime()。
	setTimeout("getDate()", 1000);
}

// 补位函数。
function extra(x) {
	// 如果传入数字小于10，数字前补一位0。
	if (x < 10) {
		return "0" + x;
	} else {
		return x;
	}
}

function hideToast() {
	var alert = document.getElementById("toast");
	alert.style.opacity = 0;
	clearInterval(intervalCounter);
}
function drawToast(message) {
	var alert = document.getElementById("toast");
	if (alert == null) {
		var toastHTML = '<div id="toast">' + message + '</div>';
		document.body.insertAdjacentHTML('beforeEnd', toastHTML);
	} else {
		alert.style.opacity = .9;
	}
	intervalCounter = setInterval("hideToast()", 1000);
}
function save() {
	drawToast("Toast······");
}

// 提交表单的时候验证是否有输入项
function checkLogin() {
	oldCount = $("#params").children().length / 2;
	if ($("#interfaceUrl").val() == "") {

		alert("有未输入的参数");
		return false;
	} else {
		for (i = 0; i < oldCount; i++) {
			if ($("#paramName" + oldCount + "").val() == ""
					|| $("#paramValue" + oldCount + "").val() == "") {
				alert("有未输入的参数");
				return false;
			}
		}
	}
}

Date.prototype.format = function(format) {
	var date = {
		"M+" : extra(this.getMonth() + 1),
		"d+" : extra(this.getDate()),
		"h+" : extra(this.getHours()),
		"m+" : extra(this.getMinutes()),
		"s+" : extra(this.getSeconds()),
		"q+" : extra(Math.floor((this.getMonth() + 3) / 3)),
		"S+" : extra(this.getMilliseconds())
	};
	if (/(y+)/i.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + '')
				.substr(4 - RegExp.$1.length));
	}
	for ( var k in date) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k]
					: ("00" + date[k]).substr(("" + date[k]).length));
		}
	}
	return format;
}
Array.prototype.remove = function(val) {
	var index = this.indexOf(val);
	if (index > -1) {
		this.splice(index, 1);
	}
};